const cloud = require('wx-server-sdk')
cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})
const db = cloud.database()
const _ = db.command

const numberFormat = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const dateTimeFormatter = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const dateStr = `${[year, month, day].map(numberFormat).join('-')}`
  const timeStr = `${[hour, minute, second].map(numberFormat).join(':')}`
  return [dateStr,timeStr]
}

/**记录待支付流水 */
const recordWaitPayOrderNo = async (event) =>{
   //订单号
   const outTradeNo = event.outTradeNo
   //交易金额
   const totalFee = Number(event.totalFee / 100)
   //手机号
   const mobile = event.mobile
   //绑定功德主信息表ID
   const kindPeopId = event.kindPeopId
   const dateTime = await dateTimeFormatter(new Date())
   const data = {
     orderNo: outTradeNo,
     chargeDate: dateTime[0],
     chargeTime: dateTime[1],
     recMerchantNo: '1609677766',
     kindPeopInfoId: kindPeopId,
     chargeMobile: mobile,
     chargeAmount: totalFee,
     chargeBeforeBalance: 0,
     chargeAfterBalance: 0,
     payStatus: '待支付',
     remark: ''
   }
   console.log('添加前的参数为：',data)
   const insertResult = await db.collection('paymentDetails').add({data: data})
   console.log('插入结果为：', insertResult)
   if(insertResult._id){
     return true
   }
   return false
}
/**
 * 1，把待支付流水改为成功流水，并更新充值前余额和充值后余额 
 * 2，更新放生明细表的余额，添加支付金额(chargeAmount)
*/
const waitPayOrderNoTransSuccessOrderNo = async (event) => {
  const orderNo = event.outTradeNo
  const queryWaitPayResult = await db.collection('paymentDetails').where({orderNo: orderNo}).get({})
  console.log('查询待支付流水结果为：',queryWaitPayResult , '\n')
  const data = queryWaitPayResult.data
  if(data.length < 0 ){
    console.error('该待支付流水不存在.\n');
    return { errcode: 0, errmsg: ''}
  }
  if(data[0].payStatus == '成功'){ 
    console.info('此交易已成功，无需再更新状态.');
    return { errcode: 0, errmsg: ''}
  }
  const chargeAmount = data[0].chargeAmount //交易金额
  const kindPeopleId = data[0].kindPeopInfoId //善主信息表ID
  const queryKindPeopleInfoResult = await db.collection('kindPersonInfo').where({_id: kindPeopleId}).get()
  console.log('查询善主表结果: ',queryKindPeopleInfoResult)
  const meritsVirtues = queryKindPeopleInfoResult.data[0].meritsVirtues
  if(meritsVirtues == undefined || meritsVirtues == ''){ 
    console.error('功德主名称不能为空.'); 
    return { errcode: 0, errmsg: ''};
  }
  try{
    //开始事物
    const transaction = await db.startTransaction()
    const queryFreeCapResult = await transaction.collection('freeCaptiveDetails').where({ meritsVirtues: meritsVirtues }).orderBy('freeDate','desc').limit(1).get()
    const freeCaptiveData = queryFreeCapResult.data
    //放生明细表中不存在，则新建今日日期的明细
    if(freeCaptiveData == undefined || freeCaptiveData == null || freeCaptiveData == ''){
      console.error('查询放生明细表为空，开始添加功德主明细，功德主名为：' + meritsVirtues )
      const dateTime = await dateTimeFormatter(new Date())
      const dataFree = {
        meritsVirtues: meritsVirtues, 
        freeDate: dateTime[0], 
        freeAmount: 0, 
        balance: Number(chargeAmount), 
        chargeAmount: Number(chargeAmount),
        isSelect: false 
      }
      console.log('添加放生明细表参数为：', dataFree)
      const addFreeCapResult = await transaction.collection('freeCaptiveDetails').add({data: dataFree})
      if(!addFreeCapResult._id){
        console.log('添加放生明细失败.事物物回滚.')
        await transaction.rollback()
        return { errcode: 0, errmsg: ''}
      }
      //更新流水表
      const updatePayOrd = await transaction.collection('paymentDetails').doc(data[0]._id).update({data: {chargeBeforeBalance: '0.00', chargeAfterBalance: chargeAmount, payStatus: '成功'}})
      console.log('更新支付流水表结果：',updatePayOrd , "\n")
      if(updatePayOrd.stats.updated != 1){
        await transaction.rollback()
        console.error('更新支付流水表失败，事务回滚.')
        return { errcode: 0, errmsg: ''}
      }
      await transaction.commit()
      console.log('事物提交成功.')
      return { errcode: 0, errmsg: ''}
    }
    const balance = freeCaptiveData[0].balance //支付前余额
    const newBalance = (Number(balance) + Number(chargeAmount)).toFixed(2) //支付后余额
    let payAmou = freeCaptiveData[0].chargeAmount //交易金额
    //如果支付金额不存在则赋值为0，金额已存在，则再加上本次充值金额
    if(!payAmou){ payAmou = 0 }
    payAmou = (Number(payAmou) + Number(chargeAmount)).toFixed(2)
    console.info('开始更新放生明细表（freeCaptiveDetails）,参数为：新余额：',newBalance,'，充值金额：',payAmou,'\n')
    //更新放生明细表
    const updateFreeCaptiveResult = await transaction.collection('freeCaptiveDetails').where({_id: freeCaptiveData[0]._id}).update({ data: { balance: newBalance, chargeAmount: payAmou}})
    if(updateFreeCaptiveResult.stats.updated != 1){
      await transaction.rollback()
      console.error('更新失败，事务回滚.')
      return { errcode: 0, errmsg: ''}
    }
    console.info('更新放生明细表结果为：',updateFreeCaptiveResult , '\n')
    console.log('开始更新支付流水表（paymentDetails），支付前余额：',balance,'支付后余额：', newBalance,'\n')
    //更新流水表
    const updatePayOrd = await transaction.collection('paymentDetails').doc(data[0]._id).update({data: {chargeBeforeBalance: balance, chargeAfterBalance: newBalance, payStatus: '成功'}})
    console.log('更新支付流水表结果：',updatePayOrd , "\n")
    if(updatePayOrd.stats.updated != 1){
      await transaction.rollback()
      console.error('更新流水表失败，事务回滚.')
      return { errcode: 0, errmsg: ''}
    }
    await transaction.commit()
    console.log('事物提交成功.')
    return { errcode: 0, errmsg: ''}
  }catch (e) {
    console.error(`事物错误，错误信息为：`, e)
    return { errcode: 0, errmsg: ''}
  }
}

module.exports = {
  waitPayOrderNoTransSuccessOrderNo,
  recordWaitPayOrderNo
}